from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View
from django.core.cache import cache

from apps.areas.models import Area
from utils.response_code import RETCODE

"""
id      name    parent_id
parent_id：意思是属于哪个城市下面的


省的数据：
    select * from tb_areas where parent_id is NULL;
市/区县
    select * from tb_areas where parent_id is XXX;
    例：select * from tb_areas where parent_id = 210000
"""


class AreasView(View):
    def get(self, request):
        parent_id = request.GET.get('area_id')
        if parent_id is None:
            # 先看缓存中有没有数据
            province_list = cache.get('pro')
            # if province_list is None:
            if not province_list:
                # 查询省
                provinces = Area.objects.filter(parent_id=None)
                # 因为使用VUE渲染，需要返回json或者字典
                # 因为通过ajax请求，需要范湖json
                # 所以要返回json
                province_list = []
                for item in provinces:
                    province_list.append({
                        'id': item.id,
                        'name': item.name,
                    })
                # 把转换的数据保存到缓存中
                cache.set('pro', province_list, 24*3600)

            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok','province_list': province_list})
        else:
            sub_list = cache.get('sub_%s' % parent_id)
            if sub_list is None:
                # 查询市/区县
                sub_areas = Area.objects.filter(parent_id=parent_id)
                sub_list = []
                for sub in sub_areas:
                    sub_list.append({
                        'id': sub.id,
                        'name': sub.name,
                    })
                cache.set('sub_%s' % parent_id, sub_list, 24*3600)
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'sub_data': sub_list})

